<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/11/6
 * Time: 11:41
 */

namespace app\common\model\teacher;


use think\Db;
use think\Model;

class TeacherEssayCatalog extends Model
{
    protected $table = 'teacher_essay_catalog';
    protected $pk = 'id';

    private static $SaveFields = ['id','name','description','rank','parent_id','picture'];
    public static function getSaveFields(): array {
        return self::$SaveFields;
    }

    public static function defaultPicture(){
        return config('news_col.defaultPic');
    }

    /**
     * @param $page
     * @param $rows
     * @return mixed
     */
    public static function manageList(int $page, int $rows) {
        $result = Db::table('teacher_essay_catalog')
            ->order('rank','asc')
            ->order('id','desc')
            ->paginate($rows,false, ['page'=>$page])
            ->toArray();
        return $result;
    }

    /**
     * @return mixed
     */
    public static function apiList() {
        $sql = <<<SQL
SELECT id,name FROM teacher_essay_catalog ORDER BY rank ASC , id DESC 
SQL;
        $list = Db::query($sql);
        return $list;
    }

    /**
     * 检查是否在使用
     *
     * @param $id
     * @return bool
     */
    public static function checkUsed($id) {
        $sql = <<<SQL
SELECT exists(
SELECT * FROM teacher_essay WHERE catalog_id=:id
) e
SQL;
        $re = Db::query($sql, ['id' => $id]);

        return $re[0]['e'] ?? false;
    }

    public static function getBranch(){
        return self::where('parent_id',0)->field('id,name')->select();
    }

    public static function findById($id){
        return self::where('id',$id)->find();
    }

    public static function findByParentId($id,$field='*',$column=false){
        if($column){
            return self::where('parent_id',$id)->column($field);
        }
        return self::where('parent_id',$id)->field($field)->order('rank desc')->select();
    }

    public static function getChildIdByDesc($desc){
        return self::alias('c')->join('teacher_essay_catalog tc','c.id=tc.parent_id','left')->where('c.description',$desc)->column('tc.id');
    }

    public static function findByDesc($desc,$field='*'){
        return self::where('description',$desc)->field($field)->find();
    }

    public static function getCatalog(){
        return self::alias('c')->join('teacher_essay_catalog tc','c.id=tc.parent_id','left')->where('c.parent_id',0)->field('tc.id,tc.parent_id,c.description as parent_desc')->select();
    }
    public static function getBrothersById($id){
        return self::where('parent_id','=',function($query) use ($id){
                $query->table('teacher_essay_catalog')->where('id',$id)->field('parent_id');
            })->column('id');
    }
}